#-*- coding:utf-8 -*-
import time
import random
import os
import sys
import exceptions
from datetime import datetime
from dateutil import tz
import unittest




import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains  

import selenium.common.exceptions
from selenium.common.exceptions import WebDriverException

#开始


####################################以下为公共函数，请不要修改
def AgaDatetime():
	est = tz.gettz('America/New_York')
	today = datetime.utcnow()
	#aganow = datetime(today.year, today.month, today.day, today.hour,today.minute,today.second,tzinfo=tz.tzutc()).astimezone(est).strftime("%m:%d:%H:%M:%S")
	aganow = datetime.now(tz.tzutc()).astimezone(est).strftime("%m:%d:%H:%M:%S")
	agadatetime = aganow.split(':')	
	return agadatetime
def Agatime():
	agadatetime = AgaDatetime()
	time = str(agadatetime[2]) + ":" + str(agadatetime[3])+":" + str(agadatetime[4])
	return time
def AgaToday():
	agadatetime =AgaDatetime()
	today = str(agadatetime[0]) + "_" + str(agadatetime[1])
	return today
def readfilerandomline(filename,path):
	if (path == ""):
		path = sys.path[0]
	f = open(os.path.join(path,filename),'rU')
	alllineinfos = f.readlines()
	filelens = len(alllineinfos)
	randline = random.randint(0,filelens-1)
	return alllineinfos[randline].strip('\n')
def readfilerline(filename,path,infoline):
	if (path == ""):
		path = sys.path[0]
	f = open(os.path.join(path,filename),'rU')
	alllineinfos = f.readlines()
	return alllineinfos[infoline].strip('\n')
def writefilerline(filename,path,infoline,value):
	if (path == ""):
		path = sys.path[0]
	f = open(os.path.join(path,filename),'rU')
	alllineinfos = f.readlines()
	alllineinfos[infoline] = str(value)+'\n'
	f = open(os.path.join(path,filename),'w')
	f.writelines(alllineinfos)
	f.close()
def writelogfileline(log,path = "C:\\ENV\\"):
	if (path == ""):
		path = sys.path[0]
	today = AgaToday()
	logfilename = "logfile_"+ today +".txt"
	logfilename = os.path.join(path,logfilename)
	if(os.path.exists(logfilename) == False):
		f = open(logfilename,'w')
		f.close()
	f = open(logfilename,'a+')
	f.writelines(log+'\n')
	f.close()
def writetmpfileline(log,filename,path = "C:\\ENV\\"):
	if (path == ""):
		path = sys.path[0]
	tmpfilename = filename
	tmpfilename = os.path.join(path,tmpfilename)
	if(os.path.exists(tmpfilename) == False):
		f = open(tmpfilename,'w')
		f.close()
	f = open(tmpfilename,'w')
	f.writelines(log+'\n')
	f.close()

def openBrowsersetprefressfx(uaFilePath ="C:\\ENV\\UAFile.txt"):
	ualininfo = readfilerandomline(uaFilePath,"")
	fp = webdriver.FirefoxProfile()
	####set S5
	#fp.set_preference("network.proxy.type", 1)
	#fp.set_preference("network.proxy.socks","127.0.0.1")
	#fp.set_preference("network.proxy.socks_port",9951)   
	#####set ua
	fp.set_preference("general.useragent.override",ualininfo)
	fp.set_preference("media.peerconnection.enabled",False)
	#add firebug
	#fp.add_extension(extension='C:\\Documents and Settings\\nini\\Application Data\\Mozilla\\Firefox\\Profiles\\1y606se6.default\\extensions\\firebug@software.joehewitt.com.xpi')
	#fp.set_preference("extensions.firebug.currentVersion", "2.0.17");#设置firebug 版本
	#active firebug extensions
	#fp.set_preference("extensions.firebug.allPagesActivation", "on");

	fp.update_preferences()
	br = webdriver.Firefox(firefox_profile=fp)
	br.set_page_load_timeout(140)
	return br
def checkwebLink():
	return1=os.system('ping 8.8.8.8')
	if return1:
		return False
	else:
		return True

def checkwebLink2():
	import subprocess
		 
	fnull = open(os.devnull, 'w')
	return1 = subprocess.call('ping 8.8.8.8', shell = True, stdout = fnull, stderr = fnull)
	if return1:
		print 'ping fail'
	else:
		print 'ping ok'
	fnull.close()

def checkProcessCount(processname):
	p = os.popen('tasklist /FI "IMAGENAME eq %s"' % processname)
	return p.read().count(processname)


def timer_start():
	t = threading.Timer(5,watch_func)
	t.start()
def watch_func(processname,reopenCmd):
	print "I'm watch_func,"
	if get_process_count(processname) < 2 : #'python.exe'
		subprocess.Popen(reopenCmd)         #"c:\python.exe"
		print "reopen"
	timer_start()
	
	
def checkUrl(curUrl,offerUrl):
	if (curUrl.find(offerUrl)==-1):
		return False
	else:
		return True
def CCleaner(filePath = "C:/CCleaner/CCleaner.exe /AUTO"):
	os.popen(filePath)#/AUTO
#####################################以上为公共函数，请不要修改




###################################################################以下为调试参数，请修改！

debug = False         #修改： 调试时设置为True
lineinfo = 47      #修改: 将要使用的资料的行编号
offerId = 39059     #修改: 对应的aga任务的id

isCheckOfferUrl = True   #可修改： True表示要设置比较最终的链接是否是任务最终的链接  False表示不检验    True需要设置下一行的pureUrl，好处是如果cap没有了，节省之间，直接很快结束
pureUrl = "cashcrate"    #可修改：如果isCheckOfferUrl设置为True，则这里要修改，比如style.fabletics.co.uk/***  这种就填"fabletics"就可以了。


isDebugUrl = False   #修改： debug 还是test,务必修改！！！！当最出事的debug 设置为True的情况下生效。 isDebugURl = True表示使用debugUrl，False表示testUrl
					 #一般建议，设置为True的时候写脚本，脚本写好之后，设置为False来最终验证脚本，因为有时候 真正的任务跳转的url页面会有点不一样。
debugUrl = "http://www.cashcrate.com/lp1"   #修改 对应offer的预览链接
testUrl = "http://tr.kqzamd.com/track/ccu.php?m=13231&c=39106" #修改  对应于offer的带affliate的链接
###################################################################调试参数结束
  
class AgaOffer(unittest.TestCase):# 不同offer只修改 test_Done函数内的部分。
	def setUp(self):
		try:
			self.printinfo = ""
			self.isSuccess = True
			if(debug == False):
				f = open(udfInputPath,'rU')
				alllineinfos = f.readlines()
				url = alllineinfos[0].strip('\n')

				infos = alllineinfos[1].strip('\n')
				self.userinfos = infos.split(',')
			else:
				if(isDebugUrl):
					url = debugUrl
				else:
					url = testUrl
				#读取userinfo文件中的一行
				userinfo = readfilerline("userInfosFile.txt","",int(lineinfo))#留意：这里的txt是放在同目录下的调试用的用户资料文件-可修改名字，建议修改本地文件名字而不改代码
				self.userinfos = userinfo.split(',')
			urlStrs = url.split('=')
			self.urlNo= 8888
			if(len(urlStrs)>2):
				self.urlNo = urlStrs[2]
			print self.urlNo
			printinfo = "start "+ str(self.urlNo) + "---------userinfo------" + self.userinfos[0]+"---------" + Agatime()
			writelogfileline(printinfo)

			if(checkwebLink()==False):                   #判断网络是否正常连接
				raise Exception("web link not connected")
			print "start firefox"
			self.driver = openBrowsersetprefressfx()   #打开浏览器
			self.driver.delete_all_cookies() #清除cookie
			self.driver.get(url)    #打开链接
			self.main_handle = self.driver.current_window_handle
			time.sleep(2)
			self.driver.maximize_window()#最大化窗口
			curUrl = self.driver.current_url
			if(isCheckOfferUrl == True):
				if(checkUrl(curUrl, pureUrl) == False):  #判断是否是offer对应的url
					raise Exception("url is not correct offer url")
		except Exception as e:
			self.isSuccess = False
			print (str(e))
			writelogfileline(str(e))            #记录错误信息
			self.tearDown()                     #扫尾工作：清cookies ，写结果。
			raise Exception("setup error")

	def test_Done(self):
		try:
			driver = self.driver
			userinfos = self.userinfos
			main_handle = self.main_handle
			################################################################
			idNo = userinfos[0]
			firstName = userinfos[5]
			lastName  = userinfos[6]
			address1  = userinfos[7]
			city  = userinfos[8]
			state  = userinfos[9]
			email  = userinfos[4]
			zipcode  = userinfos[10]
			homephone  = userinfos[11]
			workphone  = ""
			ssnNum  = ""
			birthYear  = userinfos[3]
			birthMonth  = userinfos[1]
			birthDay  = userinfos[2]
			driverLic  = ""
			driverState  = ""
			company  = ""
			routing  = ""
			bankName  = ""
			bankAccount  = ""
			positionTitle  = ""
			
			#以下是可以将当前使用的资料数据写成一个文件放在本地。如有需要可以放出来。
			'''
			printinfoTemp =("uFistname: "+firstName + "\n"+"uLastname: "+lastName +"\n"+"uAddress: "+ address1 +"\n"+"uCity: "+ city +"\n"
			+"uState: "+ state +"\n"+"uEmail: "+ email +"\n"+"uZip: "+zipcode + "\n"+"uHomephone: "+ homephone +"\n"+"uWorkphone: "+ workphone +"\n"
			+"uSsn: "+ ssnNum +"\n"+"uBirthYear: "+ birthYear +"\n"+"uBirthMonth: "+ birthMonth +"\n"+"uBirthday: "+ birthDay +"\n"
			+"uDriverLic: "+ driverLic +"\n"+"uDriverState: "+ driverState +"\n"+"uCompany: "+ company +"\n"+"uRouting: "+ routing +"\n"+"uBankname: "+ bankName +"\n"+"uBankAccount: "+ bankAccount +"\n"
			+"uPositionTitle: "+ positionTitle +"\n")
			writetmpfileline(printinfoTemp,"Current_UserInfos.txt","C:\\ENV\\")
			'''
			################################################################
			################################################################具体任务修改这里
			
			#这是几个常用的语句供参考：第一个是按需等待，发现元素后就不等了直接操作，如果一直没发现会等待30秒，返回超时
			'''
			WebDriverWait(driver, 30,0.5).until(lambda the_driver: the_driver.find_element_by_css_selector('input[placeholder = "First Name"]').is_displayed())
			ra = random.randint(0,4)
			time.sleep(1)
			driver.find_element_by_css_selector('input[placeholder = "First Name"]').send_keys(userinfos[5])
			driver.find_element_by_css_selector('select[name = "adressData_gebDatum_month"]').find_elements_by_tag_name("option")[random.randint(1,12)].click()
			time.sleep(1)
			'''
			#这里填写针对每个任务的调表脚本，建议每次翻页后都使用WebDriverWait，因为使用了不会降低速度，不使用有可能导致错误。
			#每个操作之间停留1-2秒。
			
			obj = WebDriverWait(driver, 30,0.5).until(lambda the_driver: the_driver.find_element_by_id("lp_fname"))
			obj.clear()
			obj.send_keys(firstName)
			time.sleep(2)
			
			driver.find_element_by_id("lp_lname").clear()
			driver.find_element_by_id("lp_lname").send_keys(lastName)
			time.sleep(2)
			
			driver.find_element_by_id("lp_email").clear()
			driver.find_element_by_id("lp_email").send_keys(email)
			time.sleep(2)
			
			driver.find_element_by_id("lp_password1").clear()
			driver.find_element_by_id("lp_password1").send_keys(homephone)
			time.sleep(2)
			
			driver.find_element_by_id("lp_password2").clear()
			driver.find_element_by_id("lp_password2").send_keys(homephone)
			time.sleep(2)
			
			driver.find_element_by_id("lp_addr1").clear()
			driver.find_element_by_id("lp_addr1").send_keys(address1)
			time.sleep(2)
			
			driver.find_element_by_id("lp_addr2").clear()
			driver.find_element_by_id("lp_addr2").send_keys(address1)
			time.sleep(2)
			
			driver.find_element_by_id("lp_city").clear()
			driver.find_element_by_id("lp_city").send_keys(city)
			time.sleep(2)
			
			driver.find_element_by_id("lp_state").clear()
			driver.find_element_by_id("lp_state").send_keys(state)
			time.sleep(2)
			
			driver.find_element_by_id("lp_zip").clear()
			driver.find_element_by_id("lp_zip").send_keys(zipcode)
			time.sleep(2)
			
			driver.find_element_by_id("terms").click()
			driver.find_element_by_name("submit_btn").click()
			time.sleep(2)
			
			'''
			obj = WebDriverWait(driver, 30,0.5).until(lambda the_driver: the_driver.find_element_by_id("OI_OFFER_62867_YES"))
			obj.click()
			time.sleep(2)
			
			da = random.randint(0,1)
			if (da == 0):
				driver.find_element_by_id("OI_OFFER_85988_YES").click()
			elif (da ==1):
				driver.find_element_by_id("OI_OFFER_85988_NO").click()
			time.sleep(2)
			
			da = random.randint(0,1)
			if (da == 0):
				driver.find_element_by_id("OI_OFFER_87860_YES").click()
			elif (da ==1):
				driver.find_element_by_id("OI_OFFER_87860_NO").click()
			time.sleep(2)
			
			driver.find_element_by_id("OI_OFFER_85622_NO").click()
			time.sleep(2)
			
			driver.find_element_by_id("OI_OFFER_61050_NO").click()
			time.sleep(2)
			
			driver.find_element_by_id("OI_OFFER_89555_NO").click()
			time.sleep(2)
			
			da = random.randint(0,1)
			if (da == 0):
				driver.find_element_by_id("OI_OFFER_80941_YES").click()
			elif (da ==1):
				driver.find_element_by_id("OI_OFFER_80941_NO").click()
			time.sleep(2)
			
			driver.find_element_by_id("OI_OFFER_102235_NO").click()
			time.sleep(2)
			
			da = random.randint(0,1)
			if (da == 0):
				driver.find_element_by_id("OI_OFFER_102215_YES").click()
			elif (da ==1):
				driver.find_element_by_id("OI_OFFER_102215_NO").click()
			time.sleep(2)
			
			driver.find_element_by_id("OI_OFFER_101956_NO").click()
			time.sleep(2)
			
			driver.find_element_by_id("submit_btn").click()
			time.sleep(2)
			'''
			
			#最后一步操作，请关注以下。如果最后一步提交后，url是会变化的，则一定要使用，如果确认当前任务在url在提交后不变化，那么就注释。
			#请勿删除，如果不需要判断请修改变量以及注释*****.click()这一行
			###这个判断不是每一个都合适的，但大部分是合适的。建议使用，这样才能相对准确的统计成功的以及发现问题。
			#以下是判断submit前后的url是否一致，以判断submit是否成功。比如数据填写出错，其实不会成功，比如有些对资料 电话有要求，电话不符合要求，也不会成功
			#
			'''checkSubmitUrl = False  #修改成False表示不校验
			time.sleep(3)
			beforeurl = driver.current_url
			*********.click()   ###如果设置为True，则这里修改成最后点击提交的那步操作，如果设置为False，则这里可以注释掉。###此处必须修改或者注释！！！
			time.sleep(20)#或者获取提交后的唯一的元素作为判断，更好一点，更准确！
			afterurl = driver.current_url
			if(checkSubmitUrl == True and cmp(beforeurl,afterurl) == 0):  #判断submit前后的url是否一致，以判断submit是否成功,不足够准确
				raise Exception("the url is not changed after submit")
			'''	
		
			################################################################具体任务修改这里
			################################################################
			#等待时间，不在乎多等15秒以应对极端情况
			time.sleep(15)
			
		except Exception as msg:
			self.isSuccess = False
			print (str(msg))
			writelogfileline(str(msg))
			raise Exception("Done offer error")
			

	def tearDown(self): #扫尾工作：清cookies ，写结果。
		print "aaaaa"
		time.sleep(1)
		if(self.isSuccess == True):
			self.printinfo = "SUCCESS "+ str(self.urlNo) + "---------userinfo------" + self.userinfos[0]+"----------"+ Agatime()
		else:
			self.printinfo = "FAIL "+ str(self.urlNo) + "---------userinfo------" + self.userinfos[0]+"----------"+ Agatime()
		writelogfileline(self.printinfo)
		#self.driver.delete_all_cookies()
		time.sleep(8)
		self.driver.quit()


suite = unittest.TestSuite()
suite.addTest(AgaOffer('test_Done'))
runner=unittest.TextTestRunner()
runner.run(suite)






